package com.cotte.flow.util;

import java.util.concurrent.TimeUnit;

import com.cotte.config.ProUtil;

import io.dgraph.DgraphClient;
import io.dgraph.DgraphGrpc;
import io.dgraph.DgraphGrpc.DgraphStub;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Metadata;
import io.grpc.Metadata.Key;
import io.grpc.MethodDescriptor;
import io.grpc.stub.MetadataUtils;

public class Client {
	
	//private static final String TEST_HOSTNAME="106.12.146.108";
	//private static final String TEST_HOSTNAME="172.16.77.81";
	//private static final int TEST_PORT = 9080;
	//创建一个客户端
	public static DgraphClient createDgraphClient(boolean withAuthHeader) {
		System.out.println("TEST_HOSTNAME:"+ProUtil.TEST_HOSTNAME);
		System.out.println("TEST_PORT:"+ProUtil.TEST_PORT);
		ManagedChannel channel = ManagedChannelBuilder.forAddress(ProUtil.TEST_HOSTNAME, ProUtil.TEST_PORT)
				.usePlaintext(true).build();
		DgraphStub stub = DgraphGrpc.newStub(channel);
		
		//setting deadlines(client 的截止日期）
		ClientInterceptor timeoutInterceptor = new ClientInterceptor(){
			  @Override
			  public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
			      MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
			    return next.newCall(method, callOptions.withDeadlineAfter(500, TimeUnit.MILLISECONDS));
			  }
			};
		stub.withInterceptors(timeoutInterceptor);
		/**
		 * Setting Metadata Headers
		 * 用于身份验证
		 * Below is an example of setting a header with the name "auth-token"
		 */
		if(withAuthHeader) {
			Metadata metadata = new Metadata();
			Key<String> key = Metadata.Key.of("auth-token", Metadata.ASCII_STRING_MARSHALLER);
			String value = "the-auth-token-value";
			metadata.put(key, value);
			stub = MetadataUtils.attachHeaders(stub, metadata);
		}
		DgraphClient dgraphClient = new DgraphClient(stub);
		return dgraphClient;
		
	}
}
